import React, { Component } from "react";
import { SearchBar } from "antd-mobile";
import "./SearchCenter.scss";
import { searchGoods } from "../../../utils/dataApi";
import { withRouter } from "react-router-dom";
import PageNav from "../../PageNav";

class SearchCenter extends Component {
  state = {
    goodsList: [],
  };
  //设置一个防抖的计时器
  timeId = null;
  valid = true; // 标识上次事件是否已经完成

  // 防抖函数--以最后的那次为准
  debounce = (fn, time) => {
    if (this.timeId) {
      clearTimeout(this.timeId);
      this.timeId = null;
    }
    this.timeId = setTimeout(fn, time);
  };
  // 节流函数--每间隔多少秒触发一次
  /* throttle = (fn, timeout) => {
    if (this.vaild) {
      this.valid = false;
      setTimeout(() => {
        fn.call(this);
        this.valid = true;
      }, timeout);
    }
  }; */

  handleChange = (value) => {
    this.debounce(async () => {
      let res = await searchGoods({
        query: value,
      });
      this.setState({
        goodsList: res.message || [],
      });
    },500);
  };

  handleItemClick = (goods_id) => {
    this.props.history.push("goodsDetail/" + goods_id);
  };

  render() {
    return (
      <div className="scListItem">
        <PageNav title="搜索中心" left={true}></PageNav>

        {/* 搜索中心输入框 */}
        <SearchBar
          placeholder="Search"
          cancelText="搜索"
          // 内容改变的时候触发
          onChange={this.handleChange}
        />

        {/* 产品列表 */}
        <div className="scList">
          {this.state.goodsList.map((v) => {
            return (
              <div
                className="scListItem"
                onClick={this.handleItemClick.bind(this, v.goods_id)}
                key={v.goods_id}
              >
                {v.goods_name}
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

export default withRouter(SearchCenter);
